
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Expressions;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;

using System.Linq.Dynamic.Core;
 using Microsoft.EntityFrameworkCore; 

using DualControl.ControlMeasures.Authorization;
using DualControl.ControlMeasures.Dtos;
using DualControl.ControlMeasures;
using Abp.Runtime.Session;
using Abp.Dapper.Repositories;

namespace DualControl.ControlMeasures
{
    /// <summary>
    /// ControlMeasure应用层服务的接口实现方法  
    ///</summary>
   // [AbpAuthorize(ControlMeasureAppPermissions.ControlMeasure)]
    public class ControlMeasureAppService : DualControlAppServiceBase, IControlMeasureAppService
    {
        private readonly IRepository<ControlMeasure, int> _controlmeasureRepository;

        private readonly IDapperRepository<ControlMeasure> _controlMeasuredapperRepository;

       // private readonly IControlMeasureManager _controlmeasureManager;

        /// <summary>
        /// 构造函数 
        ///</summary>
        public ControlMeasureAppService(
        IRepository<ControlMeasure, int> controlmeasureRepository, 
        //IControlMeasureManager controlmeasureManager,
        IDapperRepository<ControlMeasure> controlMeasuredapperRepository
            )
        {
            _controlmeasureRepository = controlmeasureRepository;
           // _controlmeasureManager = controlmeasureManager;
            _controlMeasuredapperRepository = controlMeasuredapperRepository;
        }


        /// <summary>
        /// 获取ControlMeasure的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<ControlMeasureListDto>> GetPagedControlMeasures(GetControlMeasuresInput input)
        {

            var query = _controlmeasureRepository.GetAll();
            // TODO:根据传入的参数添加过滤条件

            var controlmeasureCount = await query.CountAsync();

            var controlmeasures = await query
                    .OrderBy(input.Sorting).AsNoTracking()
                    .PageBy(input)
                    .ToListAsync();

            // var controlmeasureListDtos = ObjectMapper.Map<List <ControlMeasureListDto>>(controlmeasures);
            var controlmeasureListDtos = controlmeasures.MapTo<List<ControlMeasureListDto>>();

            return new PagedResultDto<ControlMeasureListDto>(
            controlmeasureCount,controlmeasureListDtos
                );
        }


        /// <summary>
        /// 通过指定id获取ControlMeasureListDto信息
        /// </summary>
        public async Task<ControlMeasureListDto> GetControlMeasureByIdAsync(EntityDto<int> input)
        {
            var entity = await _controlmeasureRepository.GetAsync(input.Id);

            return entity.MapTo<ControlMeasureListDto>();
        }

        /// <summary>
        /// MPA版本才会用到的方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<GetControlMeasureForEditOutput> GetControlMeasureForEdit(NullableIdDto<int> input)
        {
            var output = new GetControlMeasureForEditOutput();
            ControlMeasureEditDto controlmeasureEditDto;

            if (input.Id.HasValue)
            {
                var entity = await _controlmeasureRepository.GetAsync(input.Id.Value);

                controlmeasureEditDto = entity.MapTo<ControlMeasureEditDto>();

                //controlmeasureEditDto = ObjectMapper.Map<List <controlmeasureEditDto>>(entity);
            }
            else
            {
                controlmeasureEditDto = new ControlMeasureEditDto();
            }

            output.ControlMeasure = controlmeasureEditDto;
            return output;
        }


        //新增管控措施：一个作业步骤对应多条管控措施
        //支持一次新增多条

        public async Task InsertControlMeasures(int HazardSourceId, string[] ControlMeasures)
        {
            var tenantid = AbpSession.GetTenantId();

            foreach (var controlstring in ControlMeasures)
            {
                if (ControlMeasures.Length > 0)
                {
                    var controlMeasure = new ControlMeasure() { HazardSourceId = HazardSourceId,TenantId = tenantid,ControlContent = controlstring };
                    await _controlMeasuredapperRepository.QueryAsync("insert into HazardSources (RiskPointId,JobStep,TenantId,IsDeleted) values (@RiskPointId,@JobStep,@TenantId,@IsDeleted)", controlMeasure);
                }
            }

        }


        /// <summary>
        /// 添加或者修改ControlMeasure的公共方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task CreateOrUpdateControlMeasure(CreateOrUpdateControlMeasureInput input)
        {

            if (input.ControlMeasure.Id.HasValue)
            {
                await UpdateControlMeasureAsync(input.ControlMeasure);
            }
            else
            {
                await CreateControlMeasureAsync(input.ControlMeasure);
            }
        }


        /// <summary>
        /// 新增ControlMeasure
        /// </summary>
       // [AbpAuthorize(ControlMeasureAppPermissions.ControlMeasure_Create)]
        protected virtual async Task<ControlMeasureEditDto> CreateControlMeasureAsync(ControlMeasureEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            var entity = ObjectMapper.Map<ControlMeasure>(input);

            entity = await _controlmeasureRepository.InsertAsync(entity);
            return entity.MapTo<ControlMeasureEditDto>();
        }

        /// <summary>
        /// 编辑ControlMeasure
        /// </summary>
      //  [AbpAuthorize(ControlMeasureAppPermissions.ControlMeasure_Edit)]
        protected virtual async Task UpdateControlMeasureAsync(ControlMeasureEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新

            var entity = await _controlmeasureRepository.GetAsync(input.Id.Value);
            input.MapTo(entity);

            // ObjectMapper.Map(input, entity);
            await _controlmeasureRepository.UpdateAsync(entity);
        }



        /// <summary>
        /// 删除ControlMeasure信息的方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
     //   [AbpAuthorize(ControlMeasureAppPermissions.ControlMeasure_Delete)]
        public async Task DeleteControlMeasure(EntityDto<int> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _controlmeasureRepository.DeleteAsync(input.Id);
        }



        /// <summary>
        /// 批量删除ControlMeasure的方法
        /// </summary>
     //   [AbpAuthorize(ControlMeasureAppPermissions.ControlMeasure_BatchDelete)]
        public async Task BatchDeleteControlMeasuresAsync(List<int> input)
        {
            //TODO:批量删除前的逻辑判断，是否允许删除
            await _controlmeasureRepository.DeleteAsync(s => input.Contains(s.Id));
        }


        /// <summary>
        /// 导出ControlMeasure为excel表,等待开发。
        /// </summary>
        /// <returns></returns>
        //public async Task<FileDto> GetControlMeasuresToExcel()
        //{
        //	var users = await UserManager.Users.ToListAsync();
        //	var userListDtos = ObjectMapper.Map<List<UserListDto>>(users);
        //	await FillRoleNames(userListDtos);
        //	return _userListExcelExporter.ExportToFile(userListDtos);
        //}



        //// custom codes

        //// custom codes end

    }
}


